package dao.impl;

import dao.UserDao;
import pojo.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class UserDaoImpl implements UserDao {

    @Override
    public List<User> findAll() {
        //TODO
        List<User> list = new ArrayList<>();


        //jdbc操作数据库
        Connection connection = null;
        PreparedStatement preparedStatement =null;
        ResultSet resultSet =null;

        try {
            //1.加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.创建连接
            String url = "jdbc:mysql://127.0.0.1:3306/jdbc?characterEncoding=utf-8";
            connection = DriverManager.getConnection(url, "root", "GYF914413..");
            //3.sql语句
            String sql = "SELECT * FROM user";
            //4.预编译sql
            preparedStatement = connection.prepareStatement(sql);
            //设置参数

            //5.执行sql
            resultSet = preparedStatement.executeQuery();
            //6.遍历结果
            while(resultSet.next()){
                User user = new User();
                user.setId(resultSet.getInt("id"));
                user.setName(resultSet.getString("name"));
                user.setPass(resultSet.getString("pass"));
                list.add(user);
            }
            return list;

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            //7.关闭资源
            try {
                if(resultSet!=null){
                    resultSet.close();
                }
                if(preparedStatement!=null){
                    preparedStatement.close();
                }
                if(connection!=null){
                    connection.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }

        }


    }
}